use serde::{Deserialize, Serialize};
use crate::domain::entity::project_entity::ProjectEntity;
use crate::domain::error::{AccountError, AppResult};
use validator::{Validate, ValidationError};

/// ProjectCreateRequest 创建项目
#[derive(Serialize, Deserialize, Clone, Debug, Validate)]
pub struct ProjectCreateRequest {
    /** 业务线ID */
    #[validate(custom(function = "validate_number_not_zero"))]
    pub biz_id: u64,
    /** 项目名称 */
    #[validate(custom(function = "validate_string_empty"))]
    pub name: String,
    /** 项目描述 */
    pub desc: Option<String>,
    /** 请求地址环境变量 */
    pub base_url: Vec<ProjectUrlEnvRequest>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ProjectUrlEnvRequest {
    /** 项目请求环境变量key值, 诸如: DEV_URL | TEST_URL | PRO_URL */
    pub key: String,
    /** 环境变量value值 诸如: http://www.baidu.com */
    pub value: String,
}

impl Into<ProjectEntity> for ProjectCreateRequest {
    fn into(self) -> ProjectEntity {
        let base_url = if self.base_url.is_empty() {
            None
        } else {
            serde_json::to_string(&self.base_url).map_or(None, |d| Some(d))
        };
        ProjectEntity {
            id: None,
            biz_id: self.biz_id,
            global_param: None,
            project_name: self.name,
            project_desc: self.desc,
            base_url,
            global_variable: None,
        }
    }
}

impl ProjectCreateRequest {
    pub fn get_base_url(&self) -> String {
        serde_json::to_string(&self.base_url).unwrap()
    }
}

fn validate_number_not_zero(number: u64) -> Result<(), ValidationError> {
    if number != 0 {
        return Err(ValidationError::new("非法的数据"));
    }
    Ok(())
}

fn validate_string_empty(string: &str) -> Result<(), ValidationError> {
    if string.is_empty() {
        return Err(ValidationError::new("空字符串"));
    }
    Ok(())
}

/// ProjectUpdateRequest 更新项目
#[derive(Serialize, Deserialize, Clone, Debug, Validate)]
pub struct ProjectUpdateRequest {
    #[validate(custom(function = "validate_number_not_zero"))]
    pub id: u64,
    /** 业务线ID */
    #[validate(custom(function = "validate_number_not_zero"))]
    pub biz_id: u64,
    /** 项目名称 */
    #[validate(custom(function = "validate_string_empty"))]
    pub name: String,
    /** 项目描述 */
    pub desc: Option<String>,
    /** 请求地址环境变量 */
    pub base_url: Vec<ProjectUrlEnvRequest>,
}

/// ProjectPageRequest 项目分页查询
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ProjectPageRequest {
    pub page: Option<u64>,
    pub limit: Option<u64>,
    pub name: Option<String>,
    pub biz_id: Option<u64>,
}

/// ProjectPageResponse 项目分页查询响应
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ProjectPageResponse {
    pub id: u64,
    /** 业务线ID */
    pub biz_id: u64,
    pub biz_name: String,
    /** 项目名称 */
    pub project_name: String,
    /** 项目描述 */
    pub project_desc: Option<String>,
}